import type { ThemeMode, ThemeVariables } from "@/types/theme";
import type { ThemeState } from "./state";
import { defaultDarkTheme, defaultLightTheme } from "./state";

// 应用主题变量到 CSS 变量
function applyTheme(variables: ThemeVariables) {
	const root = document.documentElement;
	Object.entries(variables).forEach(([key, value]) => {
		// 转换驼峰命名为短横线命名
		const cssKey = key.replace(/([A-Z])/g, "-$1").toLowerCase();
		root.style.setProperty(`--${cssKey}`, value);
	});
}

export const actions = {
	// 初始化主题
	initTheme(this: ThemeState) {
		// 监听系统主题变化
		window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", e => {
			this.systemIsDark = e.matches;
			if (this.mode === "system") {
				this.variables = e.matches ? defaultDarkTheme : defaultLightTheme;
				applyTheme(this.variables);
			}
		});

		// 应用初始主题
		if (this.mode === "system") {
			this.variables = this.systemIsDark ? defaultDarkTheme : defaultLightTheme;
		} else {
			this.variables = this.mode === "dark" ? defaultDarkTheme : defaultLightTheme;
		}
		applyTheme(this.variables);
	},

	// 设置主题模式
	setMode(this: ThemeState, mode: ThemeMode) {
		this.mode = mode;
		if (mode === "system") {
			this.variables = this.systemIsDark ? defaultDarkTheme : defaultLightTheme;
		} else {
			this.variables = mode === "dark" ? defaultDarkTheme : defaultLightTheme;
		}
		applyTheme(this.variables);
	},

	// 自定义主题变量
	customizeTheme(this: ThemeState, customVariables: Partial<ThemeVariables>) {
		this.variables = {
			...this.variables,
			...customVariables,
		};
		applyTheme(this.variables);
	},
};
